/**
 * 
 */
package com.streaminggbs.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.streaminggbs.common.utils.RedisUtil;

/**
 * @author Yisony
 *
 */
@Service
@SuppressWarnings("unchecked")
public class VideoServerStatusService {

	private static final String REDIS_SYS_STATUS_INFO_KEY_PREFIX = "SYS_STATUS_INFO:";

	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private ObjectMapper objectMapper;

	public List<Map<String, Object>> getBandwidth(String serverId) throws JsonMappingException, JsonProcessingException {
		return getList(serverId, "bandwidth");
	}

	public List<Map<String, Object>> getMemory(String serverId) throws JsonMappingException, JsonProcessingException {
		return getList(serverId, "memory");
	}

	public List<Map<String, Object>> getCPU(String serverId) throws JsonMappingException, JsonProcessingException {
		return getList(serverId, "cpu");
	}

	public Map<String, Object> getDisk(String serverId) throws JsonMappingException, JsonProcessingException {
		return getMap(serverId, "disk");
	}

	public Map<String, Object> getFlow(String serverId) throws JsonMappingException, JsonProcessingException {
		return getMap(serverId, "flow");
	}

	private Map<String, Object> getMap(final String serverId, final String module) throws JsonMappingException, JsonProcessingException {
		Object raw = redisUtil.get(REDIS_SYS_STATUS_INFO_KEY_PREFIX + serverId + ":" + module);
		return null == raw ? new HashMap<>(0) : objectMapper.readValue((String) raw, Map.class);
	}

	private List<Map<String, Object>> getList(final String serverId, final String module) throws JsonMappingException, JsonProcessingException {
		List<Object> rawList = redisUtil.lGet(REDIS_SYS_STATUS_INFO_KEY_PREFIX + serverId + ":" + module, 0, -1);
		if (null == rawList) {
			return new ArrayList<>(0);
		}
		List<Map<String, Object>> res = new ArrayList<>(rawList.size());
		for (Object item : rawList) {
			res.add(objectMapper.readValue((String) item, Map.class));
		}
		return res;
	}

}
